﻿using System;
using Core.DataAccess.Model.Project.Queue;
using Core.Framework.Model.ViewModel;
using Core.Framework.Model.WebSockets;
using Core.Web.Model;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Net.WebSockets;
using System.Collections.Generic;
using System.Threading.Tasks;
using Core.Framework.Model.Common;
using Core.Web.Controllers.Socket.AcceptModel;
using Core.IBusiness.IProjectModule.Model;
using SqlSugar;
using Core.IBusiness.IUserModule.Model;
using Core.Framework.Util;
using Core.IBusiness.IUserModule;
using Core.IBusiness.ISDK;

namespace Core.Web.Controllers.Socket
{
    /// <summary>
    /// 用户信息
    /// </summary>
    [Route(".v1/socket/[controller]")]
    [ApiController]
    [ApiBaseController]
    public class UserController : BaseApiController
    {
        public UserController(ISocketUser iSocketUser, ISMS iSMS) : 
            base(iSocketUser: iSocketUser, iSMS: iSMS) {
        
        }

        [HttpGet(".getproejct")]
        public IResult Gettt() {
            
                var result = this.iSocketUser.GetProjectInfo();

            return new ApiResult
            {
                code = CodeResult.SUCCESS ,
                date = result
            };
        }

        /// <summary>
        /// 获取用户信息根据Token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IResult Get()
        {
            var result = this.iSocketUser.GetUserInfoByToken(iClientInfo.Token, iProjectInfo.Token);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.PERMISSION_NO_ACCESS,
                date = result.Date,
                info = result.Discription
            };
        }

        /// <summary>
        /// 客户端缓存用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet(".cAll")]
        [IgnoreAuthorize]
        public IResult GetAll()
        {
            var result = this.iSocketUser.GetUserInfoAll(iProjectInfo.Token);

            var local = new Dictionary<int, LocalClientInfo>();

            if (result.IsFinished)
            {
                foreach (var item in result.Date)
                {

                    var model = new LocalClientInfo();

                    if (!string.IsNullOrWhiteSpace(item.Paras))
                    {
                        var uuuu = item.Paras.TryToJObject();
                        model.headImg = uuuu?["headImg"]?.ToString();
                        model.userName = uuuu?["userName"]?.ToString();
                    }

                    local.Add(item.Id, model);

                }
            }

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = local
            };
        }


        /// <summary>
        /// 短信注册用户
        /// </summary>
        /// <returns></returns>
        [HttpPost(".smsUserReg")]
        [IgnoreAuthorize]
        public IResult SmsUserReg(SMSRequest request)
        {
            var result = this.iSMS.UserReg(request.toPhone, iProjectInfo.Title);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date,
                info = result.Discription
            };
        }



        /// <summary>
        /// 短信用户绑定手机号
        /// </summary>
        /// <returns></returns>
        [HttpPost(".smsUserBindPhone")]
        public IResult SmsUserBindPhone(SMSRequest request)
        {
            var result = this.iSMS.UserBingPhone(request.toPhone, iProjectInfo.Title);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date
            };
        }


        /// <summary>
        /// 短信用户修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost(".smspass")]
        [IgnoreAuthorize]
        public IResult SmsUserUpdatePassword(SMSRequest request)
        {
            var result = this.iSMS.UserUpdatePassword(request.toPhone, iProjectInfo.Title);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date
            };
        }


        /// <summary>
        /// 短信用户登录
        /// </summary>
        /// <returns></returns>
        [HttpPost(".smslogin")]
        [IgnoreAuthorize]
        public IResult SmsLogin(SMSRequest request)
        {
            var result = this.iSMS.UserLogin(request.toPhone, iProjectInfo.Title);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date
            };
        }




        /// <summary>
        /// 通用短信验证码
        /// </summary>
        /// <returns></returns>
        [HttpPost(".sms")]
        [IgnoreAuthorize]
        public IResult Sms(SMSRequest request)
        {
            string code = new Random().Next(100000, 999999).ToString();

            var result = this.iSMS.Plus(request.toPhone, code, iProjectInfo.Title, IBusiness.ISDK.Model.MsgTypeEnum.通用);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                info = result.Discription,
                date = code
            };
        }





        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="model">查询模型</param>
        /// <returns></returns>
        [HttpPost(".All")]
        public IResult GetAll(UserSearchRequest model)
        {

            model.LayerTable();

            return this.ExecMethod(
                () => {
                    return this.Result(this.iSocketUser
                        .GetUserInfoAll(
                            model.startTime.ObjToDate(),
                            model.endTime.ObjToDate(),
                            model.search,
                            iProjectInfo.Token,
                            model.pagination), model.pagination);
                });
            
        }


        /// <summary>
        /// 获取用户信息根据关键字
        /// </summary>
        /// <param name="userid">用户关键字</param>
        /// <returns></returns>
        [HttpGet("{userID}")]
        [IgnoreAuthorize]
        public IResult GetByUserId(int userid)
        {
            var result = this.iSocketUser.LoginByKey(userid, iProjectInfo.Token, 24 * 3);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date,
                info = result.Discription
            };
        }

        /// <summary>
        /// 获取用户信息根据关键字并设置缓存
        /// </summary>
        /// <param name="userid">用户关键字</param>
        /// <param name="hour">缓存时间/H</param>
        /// <returns></returns>
        [HttpGet("{userID}/{hour}h")]
        [IgnoreAuthorize]
        public IResult GetByCache(int userid, int hour)
        {
            var result = this.iSocketUser.LoginByKey(userid, iProjectInfo.Token, hour);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date,
                info = result.Discription
            };
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [IgnoreAuthorize]
        public IResult Reg(ProjectModuleUser model)
        {

            model.ProjectToken = iProjectInfo.Token;

            var result = this.iSocketUser.Reg(model);
            return new ApiResult
            {
                code = result.Item1 ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Item2,
                info = result.Item3
            };
        }

        /// <summary>
        /// 根据用户名密码登陆
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost(".user")]
        [IgnoreAuthorize]
        public IResult Login(LoginByUser request)
        {
            request.ApiProjectInfo = iProjectInfo;
            var result = this.iSocketUser.Login(request);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date,
                info = result.Discription
            };
        }

        /// <summary>
        /// 根据手机号密码登陆
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost(".phone")]
        [IgnoreAuthorize]
        public IResult LoginByPhone(LoginByPhone request)
        {
            request.ApiProjectInfo = iProjectInfo;
            var result = this.iSocketUser.LoginByPhone(request);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date,
                info = result.Discription
            };
        }


        /// <summary>
        /// 根据手机号短信验证码登陆
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost(".phoneCode")]
        [IgnoreAuthorize]
        public IResult LoginByClientCode(LoginByPhoneCode request)
        {
            request.ApiProjectInfo = iProjectInfo;
            var result = this.iSocketUser.LoginByClientCode(request);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date,
                info = result.Discription
            };
        }



        
        /// <summary>
        /// 根据UUID登陆
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost(".client")]
        [IgnoreAuthorize]
        public IResult LoginByClient(LoginByUUID request)
        {

            request.ApiProjectInfo = iProjectInfo;

            var result = this.iSocketUser.LoginByClient(request);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date,
                info = result.Discription
            };
        }

        /// <summary>
        /// 根据微信OPENID登陆
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost(".wchat")]
        [IgnoreAuthorize]
        public IResult LoginByWChat(LoginByWChat request)
        {
            request.ApiProjectInfo = iProjectInfo;
            var result = this.iSocketUser.LoginByWChat(request);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date,
                info = result.Discription
            };
        }

        /// <summary>
        /// 微信小程序登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost(".wchatmin")]
        [IgnoreAuthorize]
        public IResult LoginByWChatOpid(LoginByWChatMin request) 
        {

            request.ApiProjectInfo = this.iProjectInfo;
            var result = this.iSocketUser.LoginByWChatMin(request);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date,
                info = result.Discription
            };
        }

        /// <summary>
        /// 支付宝小程序登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost(".alimin")]
        [IgnoreAuthorize]
        public IResult LoginByAliOpid(LoginByAliMin request)
        {

            request.ApiProjectInfo = this.iProjectInfo;

            var result = this.iSocketUser.LoginByALiMin(request);

            return new ApiResult
            {
                code = result.IsFinished ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND,
                date = result.Date,
                info = result.Discription
            };
        }



        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        [IgnoreAuthorize]
        public IResult UpdateUserInfo(ProjectModuleUser model)
        {
            model.ProjectToken = this.iProjectInfo.Token;
            var result = this.iSocketUser.UpdateUserInfo(model);

            return new ApiResult
            {
                code = result == null ? CodeResult.PARAMS_TYPE_ERROR : CodeResult.SUCCESS,
                date = result
            };
        }

        /// <summary>
        /// 修改用户扩展参数
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut(".paras")]
        public IResult UpdateUserInfoParas(ProjectModuleUser model)
        {
            model.Id = iClientInfo.Key;
            model.Token = iClientInfo.Token;
            model.ProjectToken = iProjectInfo.Token;

            var result = this.iSocketUser.UpdateUserInfoParas(model.Id,model.Token,model.ProjectToken,model.Paras);

            return new ApiResult
            {
                code = model == null ? CodeResult.PARAMS_TYPE_ERROR : CodeResult.SUCCESS,
                date = result
            };
        }

        /// <summary>
        /// 退出登陆根据用户Token
        /// </summary>
        [HttpDelete]
        public void OutLogin()
        {
            this.iSocketUser.OutLogin(iClientInfo.Token, iProjectInfo.Token);
            {
                //WebSocketApplication.ClientsPool
                // 处理 客户机下线
            }
        }

        /// <summary>
        /// 退出SocketClient根据ServiceToken
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpDelete(".wsbyservice{token}")]
        public IResult OutLoginByServiceToken(string token)
        {
            var clients = WebSocketApplication.ClientsPool
                    .Where(a => a.Key.State == WebSocketState.Open && a.Value.ServiceToken == token);

            // 判断是否在线
            if (clients.Count() > 0)
            {
                // 下线
                foreach (var item in clients)
                {
                    WebSocketApplication.ClientLoginOut(item.Key);
                }
            }

            return new ApiResult
            {
                code = CodeResult.SUCCESS
            };
        }

        /// <summary>
        /// 退出SocketClient根据ClientToken
        /// </summary>
        /// <returns></returns>
        [HttpDelete(".ws")]
        public IResult WsOutLogin()
        {
            var clients = WebSocketApplication.ClientsPool
                    .Where(a => a.Key.State == WebSocketState.Open && a.Value.ClientToken == iClientInfo.Token);

            // 判断是否在线
            if (clients.Count() > 0)
            {
                // 下线
                foreach (var item in clients)
                {
                    WebSocketApplication.ClientLoginOut(item.Key);
                }
            }


            return new ApiResult
            {
                code =  CodeResult.SUCCESS
            };

        }

    }
}
